package com.why.codec;


import com.why.enums.PackageType;
import com.why.message.RpcRequest;
import com.why.serializable.CommonSerializable;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;


/**
 * @program: whyrpcframework
 * @description:对发送的数据进行序列化
 * @author: @why
 * @create: 2021-03-11 18:51
 **/
@Slf4j
public class CommonEncoder extends MessageToByteEncoder {

    private static final int MAGIC_NUMBER = 0xCAFEBABE;
    //自定义的序列化
    private final CommonSerializable commonSerial;

    public CommonEncoder(CommonSerializable commonSerial) {
        this.commonSerial = commonSerial;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        log.info("开始加密");
            out.writeInt(MAGIC_NUMBER);
            //如果msg是请求，那就进行请求的编码
            if(msg instanceof RpcRequest){
                log.info("开始对请求信息进行编码");
                out.writeInt(PackageType.REQUEST_PACK.getCode());
            }else {
                log.info("开始对响应信息进行编码");
                out.writeInt(PackageType.RESPONSE_PACK.getCode());
            }
        /**
         * 按照顺序写出数据
         * 序列化类型，数据长度，数据。
         */
        System.out.println("序列化码："+commonSerial.getCode());
        out.writeInt(commonSerial.getCode());
        byte[] bytes = commonSerial.serialize(msg);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);


    }

}
